import { ajaxData, postAPI } from 'src/api'
import { deepClone } from 'src/utils/utils.js'

const packageDictData = new Map()
const packageRemoteData = new Map()

// /**
//  * 将字符串中的大写字母转换为_+小写字母(大写字母转换后的小写字母)的蛇形命名法（snake_case）
//  * 如果输入为空或者非字符串类型，则返回空字符串
//  * @param {string} str - 需要转换的字符串
//  * @returns {string} - 转换后的蛇形命名法字符串
//  */
// const convertToSnakeCase = str => (str || '').replace(/([A-Z])/g, '_$1').toLowerCase()

export const getDictData = async (dictType = '') => {
  return new Promise((resolve, reject) => {
    const dictData = packageDictData.get(dictType) || []
    if (dictData.length) return resolve([...dictData])
    const params = { pageSize: '-1' }
    params.orderByItems = [{ orderType: 'ASC', property: 'sortId' }]
    params.andDynamicQueryItems = [{ criterion: 'andEqualTo', property: 'dictTypeCode', value: dictType }]
    postAPI('/config/api/cfgDictData/list', params, res => {
      const rows = (res.rows || []).map(el => {
        const { dictNameZhCn: labelZhCn = '', dictNameEnUs: labelEnUs = '', dictKey: key = '', dictValue: value } = el
        return { labelZhCn, labelEnUs, key, value, remark: el.remark || '' }
      })
      packageDictData.set(dictType, rows)
      resolve([...rows])
    }, err => reject(err))
  })
}
export const setDictData = (dictType, data = []) => packageDictData.set(dictType, data)

export const getRemoteData = async (key = '', url = '', method = 'post', params = {}) => {
  return new Promise((resolve, reject) => {
    const remoteData = packageRemoteData.get(key) || []
    if (remoteData.length) return resolve(deepClone(remoteData, false))
    if (!params.pageNum) params.pageNum = '1'
    if (!params.pageSize) params.pageSize = '-1'
    if (!Reflect.has(params, 'isEnable')) params.isEnable = '1'
    ajaxData(method, url, params).then(res => {
      const rows = res.rows || res.data || res || []
      packageRemoteData.set(key, rows || [])
      resolve(deepClone(rows || [], false))
    }).catch(error => reject(error))
  })
}
export const setRemoteData = (key, data = []) => packageRemoteData.set(key, data)
export const clearDictAndRemoteData = () => {
  packageDictData.clear()
  packageRemoteData.clear()
}